import axios from '../../axios';
import Api from '../../constants/Api';

export default {
  state: {
    token: '',
    menuId: '',
    tagsList: localStorage.getItem('tagList') ? JSON.parse(localStorage.getItem('tagList')) : [],
    navTree: localStorage.getItem('userNav') ? JSON.parse(window.localStorage.getItem('userNav')) : [],
  },
  getters: {
    includePageNames(state) {
      return state.tagsList.map((item) => item.name);
    },
    searchMenus(state) {
      const formatMenus = function (menus, newMenus = [], parent) {
        menus.map((item) => {
          // 判断menu类型是否为菜单
          if (item.fileName) {
            if (parent) {
              newMenus.push({
                text: parent.text.concat([item.text]),
                path: parent.path.concat([item.path]),
                type: item.type,
              });
            } else {
              newMenus.push({
                text: [item.text],
                path: [item.path],
                type: item.type,
              });
            }
          }
          // 假如有childrn，则递归
          if (item.children && item.children.length > 0) {
            let parentItem = null;
            // parent存在则合并parent对象值与当前菜单对象值，不存在则为一级菜单
            if (parent && (parent.text.length > 0 && parent.path.length > 0)) {
              parentItem = {
                text: parent.text.concat(item.text),
                path: parent.path.concat(item.path),
              };
            } else {
              parentItem = {
                text: [].concat(item.text),
                path: [].concat(item.path),
              };
            }
            formatMenus(item.children, newMenus, parentItem);
          }
        });
        return newMenus;
      };
      return formatMenus(state.navTree);
    },
  },
  mutations: {
    // 设置标签
    setTags(state, route = {}) {
      const isExist = state.tagsList.some((item) => item.path === route.fullPath);
      !isExist && state.tagsList.push({
        title: route.params.id ? `${route.meta.title}-${route.params.id}` : route.meta.title,
        path: route.fullPath,
        name: route.name,
      });
    },
    // 删除单个标签
    delTags(state, data = {}) {
      const { index } = data;
      if (state.tagsList.length === 1 && state.tagsList[0].path === '/index') {
        return;
      }
      const delItem = state.tagsList.splice(index, 1)[0];
      const item = state.tagsList[index] ? state.tagsList[index] : state.tagsList[index - 1];
      if (data.callback && typeof data.callback === 'function') {
        data.callback({
          delItem,
          item,
        });
      }
    },
    // 清空所有标签
    clearAllTags(state) {
      state.tagsList = [];
    },
  },
  actions: {
    getNavTree({ state }) {
      return axios({
        method: 'get',
        url: Api.getNavTree,
      })
        .then((res) => {
          state.navTree = res.data;
          return res;
        })
        .catch((err) => err);
    },
  },
};
